package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.IotMsgService;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备数据Service业务层处理
 *
 * @author Katana
 * @date 2025-05-26
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceServiceImpl deviceService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }
    
    /**
     * 查询设备数据列表
     *
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto ) {
        return deviceDataMapper.selectDeviceDataList(dto);
    }
    
    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }
    
    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }
    
    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }
    
    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }
    
    /**
     * 保存接收到的设备上传数据
     *
     * @param contentStr
     */
    @Transactional
    @Override
    public void saveDeviceData(String contentStr) {
        //1 将接收到的数据转换成JSON对象,并解析
        JSONObject jsonObject = JSON.parseObject(contentStr);
        if (jsonObject == null) {
            throw new BaseException("接收到的数据转换成JSON对象失败");
        }
        // 取出上报时间并进行解析
        String eventTime = jsonObject.getString("event_time");
        LocalDateTime activeTime = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'").plusHours(8);
        //1.2 取出设备上传数据 notify_data
        JSONObject notifyDataObj = jsonObject.getJSONObject("notify_data");
        if (notifyDataObj == null) {
            throw new BaseException("解析设备上传数据失败");
        }
        //1.3 取出notifyDataObj中的header,得到device_id
        JSONObject header = notifyDataObj.getJSONObject("header");
        if (header == null) {
            throw new BaseException("解析设备上传数据失败");
        }
        String deviceId = header.getString("device_id");
        
        //1.4 取出notifyDataObj中的body中的数据集合sevices
        JSONObject body = notifyDataObj.getJSONObject("body");
        if (body == null) {
            log.error("解析设备上传数据失败");
            throw new BaseException("解析设备上传数据失败");
        }
        
        //1.5获取json数组servicesArray：
        JSONArray servicesArray = body.getJSONArray("services");
        if (servicesArray == null || servicesArray.isEmpty()) {
            throw new BaseException("未解析到有效的设备服务数据");
        }
        List<IotMsgService> serviceList = JSON.parseArray(servicesArray.toJSONString(), IotMsgService.class);
        if (serviceList == null) {
            log.error("解析设备上传数据失败");
            throw new BaseException("解析设备上传数据失败");
        }
        //2 根据device_id查询设备信息
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if (device == null) {
            throw new BaseException("表中没有此设备");
        }
        //3 封装数据
        List<DeviceData> deviceDataList = new ArrayList<>();
        serviceList.forEach(x -> {
            x.getProperties().forEach((k, v) -> {
                DeviceData data = new DeviceData();
                BeanUtils.copyProperties(device, data);
                data.setId(null);
                data.setAlarmTime(activeTime);
                data.setAccessLocation(device.getBindingLocation());
                data.setFunctionId(k);
                data.setDataValue(v.toString());
                deviceDataList.add(data);
                
            });
        });
        if (CollUtil.isEmpty(deviceDataList)) {
            throw new BaseException("封装设备上传数据失败");
        }
        
        boolean result = this.saveBatch(deviceDataList);
        if (!result) {
            throw new BaseException("批量保存设备上报数据异常");
        }
        log.info("批量保存设备上报数据成功，本地保存成功{}条", deviceDataList.size());
        
        // 存入到redis  key：hash数据类型（大key，小key,  value）iot:device_last_data   iot_id
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId(), JSONUtil.toJsonStr(deviceDataList));
    }
}
